package org.atf.dp.client;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.apache.log4j.Logger;
import org.atf.controller.DpDashboardController;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;

import com.ibm.ws.security.util.Base64Coder;

//import com.ibm.misc.BASE64Encoder;

public class DPHttpsClient {

	private URL dpUrlObj = null;
	private HttpURLConnection httpUrlConnectionObj = null;
	//private HttpsURLConnection httpsUrlConnectionObj = null;

	private String username = "";

	private String password = "";
	private String authType="BASIC";
	private String soapAction="";
	private String contentType="";
	private HashMap<String, String> headers= new HashMap<String,String>();
	private  static Logger  logger = Logger.getLogger(DPHttpsClient.class);

	public DPHttpsClient() {
		try {
			dpUrlObj = new URL("http://127.0.0.1:9550");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public DPHttpsClient(String host, int port, String username, String password) throws Exception {
		setUrl("https://" + host + ":" + port);
		setUsername(username);
		setPassword(password);
	}

	public DPHttpsClient(String url) throws Exception {
		
	}
	/**
	 * Returns the Host name configured, default is 127.0.0.1
	 *
	 * @return
	 */
	public String getHost() {
		return dpUrlObj.getHost();
	}

	/**
	 * Sets the Host name to connect
	 *
	 * @param host
	 */
	public void setHost(String host) throws Exception {
		dpUrlObj = new URL(dpUrlObj.getProtocol() + "://" + host + ":" + dpUrlObj.getPort());
	}

	/**
	 * Returns the Port number configured, default is 80
	 *
	 * @return
	 */
	public int getPort() {
		return dpUrlObj.getPort();
	}

	/**
	 * Sets the Port number to connect
	 *
	 * @param port
	 */
	public void setPort(int port) throws Exception {
		dpUrlObj = new URL(dpUrlObj.getProtocol() + "://" + dpUrlObj.getHost() + ":" + port);
	}

	/**
	 * Sets the Username for authentication
	 *
	 * @param port
	 */
	public void setUsername(String username) throws Exception {
		this.username = username;
	}

	/**
	 * Sets the password for authentication
	 *
	 * @param port
	 */
	public void setPassword(String password) throws Exception {
		this.password = password;
	}

	/**
	 * Returns the qualified URL, default is http://127.0.0.1:80
	 *
	 * @return
	 */
	public String getUrl() {
		return dpUrlObj.getProtocol() + "://" + dpUrlObj.getHost() + ":" + dpUrlObj.getPort();
	}

	/**
	 * Sets the URL to connect - overrides the current host, port, protocol settings
	 *
	 * @param url
	 */
	public void setUrl(String url) throws Exception {
		dpUrlObj = new URL(url);
	}

	
	public String getAuthType() {
		return authType;
	}

	public void setAuthType(String authType) {
		this.authType = authType;
	}
	
	public void getAuthentication(){
		if(authType.equalsIgnoreCase("BASIC")){
			useBasicAuthentication();
		}
	}
	

	public String getSoapAction() {
		return soapAction;
	}

	public void setSoapAction(String soapAction) {
		this.soapAction = soapAction;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	
	
	public HashMap<String, String> getHeaders() {
		return headers;
	}

	public void setHeaders(HashMap<String, String> headers) {
		this.headers = headers;
	}

	
	public void connect(String requestMethod) throws Exception{
		logger.debug("Connecting to  SOAP " + dpUrlObj);
		
		if(dpUrlObj.getProtocol().equalsIgnoreCase("https")){		
			try{
				httpUrlConnectionObj = (HttpsURLConnection) dpUrlObj.openConnection();
			}catch (Exception e){
				logger.debug("opening the connection with auto certificate acceptor");
				CertificateHandler.installCert(getHost(), getPort());
				HttpsURLConnection.setDefaultSSLSocketFactory(CertificateHandler.getSSLContext().getSocketFactory());
				HostnameVerifier hv = new HostnameVerifier() {
					public boolean verify(String urlHostName, SSLSession session) {
						logger.debug("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
						return true;
					}
				};
				HttpsURLConnection.setDefaultHostnameVerifier(hv);
				httpUrlConnectionObj = (HttpsURLConnection) dpUrlObj.openConnection();
			}
		}else{
			httpUrlConnectionObj = (HttpURLConnection) dpUrlObj.openConnection();
		}
		logger.debug("httpUrlConnectionObj " + httpUrlConnectionObj);
		if(!username.equalsIgnoreCase("") && !password.equalsIgnoreCase("")){
			getAuthentication();
		}
	//	
		if(!soapAction.equalsIgnoreCase("")){
			setSOAPActionHeader(soapAction);
		}
		if(!contentType.equalsIgnoreCase("")){
			setContentTypeHeader(contentType);
		}
		if(!headers.isEmpty()){
			for(Map.Entry<String, String> headerMapEntry : headers.entrySet()){
				 setRequestProperty(headerMapEntry.getKey(), headerMapEntry.getValue());
			 }
		}
		if(requestMethod.equalsIgnoreCase("")){
			requestMethod="POST";
		}
		httpUrlConnectionObj.setRequestMethod(requestMethod);
		httpUrlConnectionObj.setDoOutput(true);
		httpUrlConnectionObj.connect();
		httpUrlConnectionObj.getOutputStream();
		logger.debug("httpUrlConnectionObj " + httpUrlConnectionObj);
	}
	/**
	 * Opens a connection to the specified URL
	 * XML Mgmt Calls are soap calls, so pass true 
	 * @throws Exception
	 */
	public void connect(boolean isSOAPCall) throws Exception {
		logger.debug("Connecting to " + dpUrlObj);
	//	synchronized (this) {
			if(dpUrlObj.getProtocol().equalsIgnoreCase("https")){	
				try{
					httpUrlConnectionObj = (HttpsURLConnection) dpUrlObj.openConnection();
				}catch (Exception e){
					System.err.println(e);
					logger.debug("opening the connection with auto certificate acceptor");
					CertificateHandler.installCert(getHost(), getPort());
					HttpsURLConnection.setDefaultSSLSocketFactory(CertificateHandler.getSSLContext().getSocketFactory());
					HostnameVerifier hv = new HostnameVerifier() {
						public boolean verify(String urlHostName, SSLSession session) {
							logger.debug("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
							return true;
						}
					};
					HttpsURLConnection.setDefaultHostnameVerifier(hv);
					httpUrlConnectionObj = (HttpsURLConnection) dpUrlObj.openConnection();
				}
				
			}else{
				httpUrlConnectionObj = (HttpURLConnection) dpUrlObj.openConnection();
			}
		
			useBasicAuthentication();
			if (isSOAPCall) {
				setSOAPActionHeader("");
			}
			httpUrlConnectionObj.setRequestMethod("GET");
			this.setDoOutput(true);
			httpUrlConnectionObj.connect();
			httpUrlConnectionObj.getOutputStream();
			
		//}
	}

	/**
	 * This operation is used, if the credentials are to be passed as a basic authentication token
	 *
	 */
	public void useBasicAuthentication() {
		
		String basicAuth = username + ":" + password;
		String encoding = Base64Coder.base64Encode(basicAuth);
		httpUrlConnectionObj.setRequestProperty("Authorization", "Basic " + encoding);
	}

	/**
	 * This operation is used, if the request is a soap call
	 *
	 * @param value
	 */
	private void setSOAPActionHeader(String value) {
		httpUrlConnectionObj.setRequestProperty("SOAPAction", value);
	}
	
	/**
	 * This operation is used, if the request is a soap call
	 *
	 * @param value
	 */
	private void setContentTypeHeader(String value) {
		httpUrlConnectionObj.setRequestProperty("Content-type", value);
	}

	public void setRequestProperty(String name, String value){
		httpUrlConnectionObj.setRequestProperty(name, value);
	}
	/**
	 * Sets the URLConnection's doOutput flag.
	 *
	 * @param value
	 * @return
	 */
	public boolean setDoOutput(boolean value) {
		httpUrlConnectionObj.setDoOutput(value);
		return httpUrlConnectionObj.getDoOutput();
	}

	/**
	 * Sets the URLConnection's doInput flag.
	 *
	 * @param value
	 * @return
	 */
	public boolean setDoInput(boolean value) {
		httpUrlConnectionObj.setDoInput(value);
		return httpUrlConnectionObj.getDoInput();
	}

	/**
	 * Sends the data to the specified URL connection
	 *
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public int sendData(String data) throws Exception {
		if (httpUrlConnectionObj.getDoOutput()) {
			httpUrlConnectionObj.getOutputStream().write(data.getBytes());
		} else {
			httpUrlConnectionObj.disconnect();
			throw new IllegalArgumentException("getDoOutput field not set");
		}
		return httpUrlConnectionObj.getResponseCode();
	}

	/**
	 * Reads the data from the InputStream specified and sends the read data to the specified URL Connection
	 *
	 * @param fis
	 * @return
	 * @throws Exception
	 */
	public int sendData(InputStream is) throws Exception {
		int x;
		StringBuffer sb = new StringBuffer();
		while ((x = is.read()) != -1) {
			sb.append((char) x);
		}
		// System.out.println("Message Sent: " + sb.toString());
		sendData(sb.toString());
		return httpUrlConnectionObj.getResponseCode();
	}

	/**
	 * Used to release the connection established.
	 *
	 */
	public void releaseConnection() {
		// System.out.println("Releasing Connection " + urlObj);
		httpUrlConnectionObj.disconnect();
		// System.out.println("Connection released");
	}

	/**
	 * Returns the response from the server
	 *
	 * @return
	 * @throws Exception
	 */
	public String getResponse() throws Exception {
		InputStream is = httpUrlConnectionObj.getInputStream();
		int x;
		StringBuffer sb = new StringBuffer();
		while ((x = is.read()) != -1) {
			sb.append((char) x);
		}
		return sb.toString();
	}

	/**
	 * Returns the error occured, if there is any error
	 *
	 * @return
	 * @throws Exception
	 */
	public String getError() throws Exception {
		InputStream is = httpUrlConnectionObj.getErrorStream();
		int x;
		StringBuffer sb = new StringBuffer();
		while ((x = is.read()) != -1) {
			sb.append((char) x);
		}
		return sb.toString();
	}

	/**
	 * Send the request and return the response received
	 *
	 * @param message
	 * @return
	 */
	public String sendMessage(String message) {
		String result = "";
		logger.debug("Message Sent: " + message);
		try {
			int status = sendData(message);
			logger.debug("HTTP Status: " + status);
			if (status == 200) {
				result = getResponse();
			} else {
				result = getError();
			}
		} catch (Exception e) {
			result = e.getMessage();
		}
		logger.debug("Response: " + result);
		return result;
	}

	/**
	 * Get System usage
	 *
	 * @param 
	 * @return Load, WorkList, Interval
	 */
	public HashMap<String, String> getSystemUsage(){
		String sysUsage="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
				"<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+
				    "<env:Body>"+
				        "<dp:request xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
				            "<dp:get-status class=\"SystemUsage\"/> "+
				        "</dp:request> "+
				    "</env:Body>"+
				"</env:Envelope>";
		String sysUsageResp=sendMessage(sysUsage);
		HashMap<String, String> result = new HashMap<String, String>();
		try {
			Document document = DocumentHelper.parseText(sysUsageResp);
			Element rootElelemt = document.getRootElement();
			Map map = new HashMap();
			map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
	        map.put("dp", "http://www.datapower.com/schemas/management");
	        XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:timestamp");
	        xpath.setNamespaceURIs(map);
	        Node timeStampNode = xpath.selectSingleNode(document);
	        if(timeStampNode != null)
                result.put(timeStampNode.getName(), timeStampNode.getText());
	        xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/SystemUsage/Interval");
            xpath.setNamespaceURIs(map);
            Node interval = xpath.selectSingleNode(document);
            if(interval != null)
            	result.put(interval.getName(), interval.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/SystemUsage/Load");
            xpath.setNamespaceURIs(map);
            Node load = xpath.selectSingleNode(document);
            if(load != null)
            	result.put(load.getName(), load.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/SystemUsage/WorkList");
            xpath.setNamespaceURIs(map);
            Node workList = xpath.selectSingleNode(document);
            if(workList != null)
            	result.put(workList.getName(), workList.getText());
           
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	/**
	 * FilesystemStatus
	 *@param 
	 *@return 
	
	 * 
	 */
	public HashMap<String, String> getFilesystemStatus(){
		String sysUsage="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
				"<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+
				    "<env:Body>"+
				        "<dp:request xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
				            "<dp:get-status class=\"FilesystemStatus\"/> "+
				        "</dp:request> "+
				    "</env:Body>"+
				"</env:Envelope>";
		String memoryUsageResp=sendMessage(sysUsage);
		System.out.println(memoryUsageResp);
		HashMap<String, String> result = new HashMap<String, String>();
		try {
			Document document = DocumentHelper.parseText(memoryUsageResp);
			Element rootElelemt = document.getRootElement();
			Map map = new HashMap();
			map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
	        map.put("dp", "http://www.datapower.com/schemas/management");
	        XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:timestamp");
	        xpath.setNamespaceURIs(map);
	        Node timeStampNode = xpath.selectSingleNode(document);
	        if(timeStampNode != null)
                result.put(timeStampNode.getName(), timeStampNode.getText());
	        // get the Usage
	        xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/FilesystemStatus/FreeEncrypted");
            xpath.setNamespaceURIs(map);
            Node freeEncrypted = xpath.selectSingleNode(document);
            if(freeEncrypted != null)
            	result.put(freeEncrypted.getName(), freeEncrypted.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/FilesystemStatus/TotalEncrypted");
            xpath.setNamespaceURIs(map);
            Node totalEncrypted = xpath.selectSingleNode(document);
            if(totalEncrypted != null)
            	result.put(totalEncrypted.getName(), totalEncrypted.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/FilesystemStatus/FreeTemporary");
            xpath.setNamespaceURIs(map);
            Node freeTemporary = xpath.selectSingleNode(document);
            if(freeTemporary != null)
            	result.put(freeTemporary.getName(), freeTemporary.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/FilesystemStatus/TotalTemporary");
            xpath.setNamespaceURIs(map);
            Node totalTemporary = xpath.selectSingleNode(document);
            if(totalTemporary != null)
            	result.put(totalTemporary.getName(), totalTemporary.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/FilesystemStatus/FreeInternal");
            xpath.setNamespaceURIs(map);
            Node freeInternal = xpath.selectSingleNode(document);
            if(freeInternal != null)
            	result.put(freeInternal.getName(), freeInternal.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/FilesystemStatus/TotalInternal");
            xpath.setNamespaceURIs(map);
            Node totalInternal = xpath.selectSingleNode(document);
            if(totalInternal != null)
            	result.put(totalInternal.getName(), totalInternal.getText());
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/*
	 * Get Memory Usage
	 *
	 * @param 
	 * @return 
	 */
	public HashMap<String, String> getMemoryStatus(){
		String sysUsage="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
				"<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+
				    "<env:Body>"+
				        "<dp:request xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
				            "<dp:get-status class=\"MemoryStatus\"/> "+
				        "</dp:request> "+
				    "</env:Body>"+
				"</env:Envelope>";
		String memoryUsageResp=sendMessage(sysUsage);
		//System.out.println(memoryUsageResp);
		HashMap<String, String> result = new HashMap<String, String>();
		try {
			Document document = DocumentHelper.parseText(memoryUsageResp);
			Element rootElelemt = document.getRootElement();
			Map map = new HashMap();
			map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
	        map.put("dp", "http://www.datapower.com/schemas/management");
	        XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:timestamp");
	        xpath.setNamespaceURIs(map);
	        Node timeStampNode = xpath.selectSingleNode(document);
	        if(timeStampNode != null)
                result.put(timeStampNode.getName(), timeStampNode.getText());
	        // get the Usage
	        xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/Usage");
            xpath.setNamespaceURIs(map);
            Node mUsage = xpath.selectSingleNode(document);
            if(mUsage != null)
            	result.put(mUsage.getName(), mUsage.getText());
            //TotalMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/TotalMemory");
            xpath.setNamespaceURIs(map);
            Node totalMemory = xpath.selectSingleNode(document);
            if(totalMemory != null)
            	result.put(totalMemory.getName(), totalMemory.getText());
            //UsedMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/UsedMemory");
            xpath.setNamespaceURIs(map);
            Node usedMemory = xpath.selectSingleNode(document);
            if(usedMemory != null)
            	result.put(usedMemory.getName(), usedMemory.getText());
            //FreeMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/FreeMemory");
            xpath.setNamespaceURIs(map);
            Node freeMemory = xpath.selectSingleNode(document);
            if(freeMemory != null)
            	result.put(freeMemory.getName(), freeMemory.getText());
            //FreeMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/ReqMemory");
            xpath.setNamespaceURIs(map);
            Node reqMemory = xpath.selectSingleNode(document);
            if(reqMemory != null)
            	result.put(reqMemory.getName(), reqMemory.getText());
            //HoldMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/HoldMemory");
            xpath.setNamespaceURIs(map);
            Node holdMemory = xpath.selectSingleNode(document);
            if(holdMemory != null)
            	result.put(holdMemory.getName(), holdMemory.getText());
            //HoldMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/ReservedMemory");
            xpath.setNamespaceURIs(map);
            Node reservedMemory = xpath.selectSingleNode(document);
            if(reservedMemory != null)
            	result.put(reservedMemory.getName(), reservedMemory.getText());
            //InstalledMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/InstalledMemory");
            xpath.setNamespaceURIs(map);
            Node installedMemory = xpath.selectSingleNode(document);
            if(installedMemory != null)
            	result.put(installedMemory.getName(), installedMemory.getText());
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * Get CPU Usage
	 *
	 * @param 
	 * @return 
	 */
	public HashMap<String, String> getCPUUsage(){
		String sysUsage="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
				"<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+
				    "<env:Body>"+
				        "<dp:request xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
				            "<dp:get-status class=\"CPUUsage\"/> "+
				        "</dp:request> "+
				    "</env:Body>"+
				"</env:Envelope>";
		String cpuUsageResp=sendMessage(sysUsage);
		//System.out.println(memoryUsageResp);
		HashMap<String, String> result = new HashMap<String, String>();
		
		Document document;
		try {
			document = DocumentHelper.parseText(cpuUsageResp);
			Element rootElelemt = document.getRootElement();
			Map map = new HashMap();
			map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
	        map.put("dp", "http://www.datapower.com/schemas/management");
	        XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:timestamp");
	        xpath.setNamespaceURIs(map);
	        Node timeStampNode = xpath.selectSingleNode(document);
	        if(timeStampNode != null)
	            result.put(timeStampNode.getName(), timeStampNode.getText());
	        xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/tenSeconds");
            xpath.setNamespaceURIs(map);
            Node tenSeconds = xpath.selectSingleNode(document);
            if(tenSeconds != null)
               	result.put(tenSeconds.getName(), tenSeconds.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/oneMinute");
            xpath.setNamespaceURIs(map);
            Node oneMinute = xpath.selectSingleNode(document);
            if(oneMinute != null)
            	result.put(oneMinute.getName(), oneMinute.getText()); 
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/tenMinutes");
            xpath.setNamespaceURIs(map);
            Node tenMinutes = xpath.selectSingleNode(document);
            if(tenMinutes != null)
            	result.put(tenMinutes.getName(), tenMinutes.getText()); 
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/oneHour");
            xpath.setNamespaceURIs(map);
            Node oneHour = xpath.selectSingleNode(document);
            if(oneHour != null)
            	result.put(oneHour.getName(), oneHour.getText()); 
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/oneDay");
            xpath.setNamespaceURIs(map);
            Node oneDay = xpath.selectSingleNode(document);
            if(oneDay != null)
            	result.put(oneDay.getName(), oneDay.getText()); 
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	public HashMap<String,String> getDPStatus()
    {
		HashMap<String,String>  result = new HashMap<String,String> ();
        String memoryReq = "<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
        					"<env:Body>"+
        							"<dp:request xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
        							"<dp:get-status class=\"MemoryStatus\"/>"+
        							"<dp:get-status class=\"CPUUsage\"/>"+
        							"<dp:get-status class=\"SystemUsage\"/>"+
        							"</dp:request>"+
        					"</env:Body>"
        					+ "</env:Envelope>";
        String memoryRes = sendMessage(memoryReq);
        try
        {
            Document document = DocumentHelper.parseText(memoryRes);
			Element rootElelemt = document.getRootElement();
			Map map = new HashMap();
			map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
	        map.put("dp", "http://www.datapower.com/schemas/management");
	        XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:timestamp");
	        xpath.setNamespaceURIs(map);
	        Node timeStampNode = xpath.selectSingleNode(document);
	        if(timeStampNode != null)
                result.put(timeStampNode.getName(), timeStampNode.getText());
	        // get the Usage
	        xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/Usage");
            xpath.setNamespaceURIs(map);
            Node mUsage = xpath.selectSingleNode(document);
            if(mUsage != null)
            	result.put(mUsage.getName(), mUsage.getText());
            //TotalMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/TotalMemory");
            xpath.setNamespaceURIs(map);
            Node totalMemory = xpath.selectSingleNode(document);
            if(totalMemory != null)
            	result.put(totalMemory.getName(), totalMemory.getText());
            //UsedMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/UsedMemory");
            xpath.setNamespaceURIs(map);
            Node usedMemory = xpath.selectSingleNode(document);
            if(usedMemory != null)
            	result.put(usedMemory.getName(), usedMemory.getText());
            //FreeMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/FreeMemory");
            xpath.setNamespaceURIs(map);
            Node freeMemory = xpath.selectSingleNode(document);
            if(freeMemory != null)
            	result.put(freeMemory.getName(), freeMemory.getText());
            //FreeMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/ReqMemory");
            xpath.setNamespaceURIs(map);
            Node reqMemory = xpath.selectSingleNode(document);
            if(reqMemory != null)
            	result.put(reqMemory.getName(), reqMemory.getText());
            //HoldMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/HoldMemory");
            xpath.setNamespaceURIs(map);
            Node holdMemory = xpath.selectSingleNode(document);
            if(holdMemory != null)
            	result.put(holdMemory.getName(), holdMemory.getText());
            //HoldMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/ReservedMemory");
            xpath.setNamespaceURIs(map);
            Node reservedMemory = xpath.selectSingleNode(document);
            if(reservedMemory != null)
            	result.put(reservedMemory.getName(), reservedMemory.getText());
            //InstalledMemory
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/MemoryStatus/InstalledMemory");
            xpath.setNamespaceURIs(map);
            Node installedMemory = xpath.selectSingleNode(document);
            if(installedMemory != null)
            	result.put(installedMemory.getName(), installedMemory.getText());
            
            //CUP USage
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/tenSeconds");
            xpath.setNamespaceURIs(map);
            Node tenSeconds = xpath.selectSingleNode(document);
            if(tenSeconds != null)
               	result.put(tenSeconds.getName(), tenSeconds.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/oneMinute");
            xpath.setNamespaceURIs(map);
            Node oneMinute = xpath.selectSingleNode(document);
            if(oneMinute != null)
            	result.put(oneMinute.getName(), oneMinute.getText()); 
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/tenMinutes");
            xpath.setNamespaceURIs(map);
            Node tenMinutes = xpath.selectSingleNode(document);
            if(tenMinutes != null)
            	result.put(tenMinutes.getName(), tenMinutes.getText()); 
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/oneHour");
            xpath.setNamespaceURIs(map);
            Node oneHour = xpath.selectSingleNode(document);
            if(oneHour != null)
            	result.put(oneHour.getName(), oneHour.getText()); 
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/CPUUsage/oneDay");
            xpath.setNamespaceURIs(map);
            Node oneDay = xpath.selectSingleNode(document);
            if(oneDay != null)
            	result.put(oneDay.getName(), oneDay.getText()); 
            
            //SystemLoad
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/SystemUsage/Interval");
            xpath.setNamespaceURIs(map);
            Node interval = xpath.selectSingleNode(document);
            if(interval != null)
            	result.put(interval.getName(), interval.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/SystemUsage/Load");
            xpath.setNamespaceURIs(map);
            Node load = xpath.selectSingleNode(document);
            if(load != null)
            	result.put(load.getName(), load.getText());
            xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/SystemUsage/WorkList");
            xpath.setNamespaceURIs(map);
            Node workList = xpath.selectSingleNode(document);
            if(workList != null)
            	result.put(workList.getName(), workList.getText());
        }
        catch(DocumentException e)
        {
            e.printStackTrace();
        }
        return result;
    }
	
	 public  List<String> getDomainStatus() {
		 List<String> result = new ArrayList<String>();
		 String domainSummary="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
					"<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+
					    "<env:Body>"+
					        "<dp:request xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
					            "<dp:get-status class=\"DomainSummary\"/> "+
					        "</dp:request> "+
					    "</env:Body>"+
					"</env:Envelope>";
			String domainSummaryResp=sendMessage(domainSummary);
			System.out.println(domainSummaryResp);
			 try
		        {
		            Document document = DocumentHelper.parseText(domainSummaryResp);
		            System.out.println(document.getRootElement().getName());
		            Map map = new HashMap();
		            map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
		            map.put("dp", "http://www.datapower.com/schemas/management");
		            XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/DomainSummary/Domain");
		            xpath.setNamespaceURIs(map);
		            List domainsList = xpath.selectNodes(document);
		            Node node;
		            for(Iterator iterator = domainsList.iterator(); iterator.hasNext(); result.add(node.getText()))
		                node = (Node)iterator.next();

		        }
		        catch(DocumentException e)
		        {
		            e.printStackTrace();
		        }
		        return result;
					
	 }
	 
	 public List<HashMap<String,String>> getHTTPTransactionsTimes(String domainName){
		 List<HashMap<String, String>> result= new ArrayList<HashMap<String,String>>();
		 String httpTransactions="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
					"<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+
					    "<env:Body>"+
					        "<dp:request domain=\""+domainName+"\" xmlns:dp=\"http://www.datapower.com/schemas/management\">"+
					            "<dp:get-status class=\"HTTPMeanTransactionTime2\"/> "+
					        "</dp:request> "+
					    "</env:Body>"+
					"</env:Envelope>";
		 String domainSummaryResp=sendMessage(httpTransactions);
		 System.out.println(domainSummaryResp);
		 Document document;
			try {
				document = DocumentHelper.parseText(domainSummaryResp);
				Element rootElelemt = document.getRootElement();
				Map map = new HashMap();
				map.put("env", "http://schemas.xmlsoap.org/soap/envelope/");
		        map.put("dp", "http://www.datapower.com/schemas/management");
		        XPath xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:timestamp");
		        xpath.setNamespaceURIs(map);
		        Node timeStampNode = xpath.selectSingleNode(document);
		        if(timeStampNode != null){
		        	 xpath = document.createXPath("//env:Envelope/env:Body/dp:response/dp:status/HTTPMeanTransactionTime2");
                    xpath.setNamespaceURIs(map);
                    List httTransactionNodes = xpath.selectNodes(document);
                    HashMap temp;
                    for(Iterator iterator = httTransactionNodes.iterator(); iterator.hasNext(); result.add(temp))
                    {
                        Node node = (Node)iterator.next();
                        temp = new HashMap();
//                        temp.put("timeStamp", timeStampNode.getText());
                        Element transactionsNode = (Element)node;
                        Element serviceClass = transactionsNode.element("serviceClass");
                        if(serviceClass != null)
                            temp.put("serviceClass", serviceClass.getText());
                        Element proxy = transactionsNode.element("proxy");
                        if(proxy != null)
                            temp.put("proxy", proxy.getText());
                        Element tenSeconds = transactionsNode.element("tenSeconds");
                        if(tenSeconds != null)
                            temp.put("tenSeconds", tenSeconds.getText());
                        Element oneMinute = transactionsNode.element("oneMinute");
                        if(oneMinute != null)
                            temp.put("oneMinute", oneMinute.getText());
                        Element tenMinutes = transactionsNode.element("tenMinutes");
                        if(tenMinutes != null)
                            temp.put("tenMinutes", oneMinute.getText());
                        Element oneHour = transactionsNode.element("oneHour");
                        if(oneHour != null)
                            temp.put("oneHour", oneHour.getText());
                        Element oneDay = transactionsNode.element("oneDay");
                        if(oneDay != null)
                            temp.put("oneDay", oneDay.getText());
                        temp.put("domainName", domainName);
                    }
		        }
		            
			} catch(DocumentException e)
	        {
	            e.printStackTrace();
	        }
		 return result;
	 }

	public void sendMessage(InputStream messageStream) {
		try {
			int status = sendData(messageStream);
			logger.debug("HTTP Status: " + status);
			if (status == 200) {
				logger.debug("Response :" + getResponse());
			} else {
				logger.debug("Response :" + getError());
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
//	public HashMap<String, HashMap<String, String>> getAllDatapowerData() {
//		// TODO Auto-generated method stub
//		HashMap<String, HashMap<String, String>>  results= new HashMap<String, HashMap<String, String>>();
//		HashMap<String,String> memoryStatus=getMemoryStatus();
//		HashMap<String,String> CPUUsage=getCPUUsage();
//		HashMap<String,String> systemUsage=getSystemUsage();
//		results.put("MemoryStatus", memoryStatus);
//		
//		results.put("CPUUsage", CPUUsage);
//		results.put("SystemUsage", systemUsage);
//		return results;
//	}
	public static void main(String args[]) throws Exception {
		String ip = "dpqm02.ibx.com"; // ipaddress of DataPower device
        int port = 5550; // SOMA port number
        String user = "wasadmin";
        String pass = "adminwas";  
        DPHttpsClient httpsCleintObj = new DPHttpsClient(ip, port, user, pass);
        httpsCleintObj.connect(true);		
//        HashMap<String, String> stats=httpsCleintObj.getCPUUsage();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
//        java.util.Date date = sdf.parse((String)stats.get("timestamp"));
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(date);
//        System.out.println(cal.getTime());
       // System.out.println(httpsCleintObj.getDomainStatus());
       System.out.println(httpsCleintObj.getFilesystemStatus());
		httpsCleintObj.releaseConnection();
	}

	
}